<?php

namespace app\admin\controller;
use think\Db;
use app\common\controller\Backend;
use app\api\common\WxPay;
use app\admin\model\examine\Reason;
use think\Request;
/**
 * 帖子管理
 *
 * @icon fa fa-circle-o
 */
class Circle extends Backend
{

    /**
     * Circle模型对象
     * @var \app\admin\model\Circle
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Circle;
        $this->view->assign("issaleList", $this->model->getIssaleList());
        $this->view->assign("authenList", $this->model->getAuthenList());
        $this->view->assign("isshowList", $this->model->getIsshowList());
        $this->view->assign("isshowPtList", $this->model->getIsshowPtList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $where_top='';
            $filter = $this->request->get('filter');
            $op = $this->request->get("op", '', 'trim');
            if($filter){
                $filter = json_decode($filter,true);

                $op = json_decode($op,true);
                if(isset($filter['istop'])){
                    
                    // "0":__('否'),"1":__('首页置顶'),"2":__('分类置顶'),"3":__('首页/分类置顶')
                    
       
                    if($filter['istop']=='0')
                    {
                        $where_top=" ((cate_top_endtime<".time()." or cate_top_endtime IS NULL) and (index_top_endtime<".time()." or index_top_endtime IS NULL))";
                    }
                    if($filter['istop']=='1')
                    {
                        $where_top="  (index_top_endtime>".time().")";
                    }
                    if($filter['istop']=='2')
                    {
                        $where_top="  (index_top_endtime>".time().")";
                    }
                    if($filter['istop']=='3')
                    {
                        $where_top="  (index_top_endtime>".time()." or cate_top_endtime>".time().")";
                    }
                    unset($filter['istop']);
                    unset($op['istop']);
                }
                $filter = json_encode($filter);
                $op = json_encode($op);
                Request::instance()->get(['filter'=>$filter]);
                Request::instance()->get(['op'=>$op]);
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // var_dump($where);
            // var_dump(input('isguan'));
            $isguan=input('isguan');
            $where_guan='';
            if($isguan==1)
            {
                //查询带关键词的
                //查询关键词
//                $keywords=db('circle_keywords')->column('name');
//                // var_dump($keywords);
//
//                // 使用逻辑运算符连接查询条件
//                if($keywords)
//                {
//                    // $where_guan = ['or'];
//                    foreach ($keywords as $key => $value) {
//                        // $where_guan[] = ['title', 'like', '%' . $value . '%'];
//                        if($key == 0)
//                        {
//                            $where_guan.=" title like '%".$value."%'";
//                        }
//                        else
//                        {
//                            $where_guan.=" or title like '%".$value."%'";
//                        }
//                    }
//                }
                $where_guan.= "is_see = 1";
            }
            $list = $this->model
                    ->with(['user','vehicle','carcategory','province','city','area'])
                    ->where($where)
                    ->where($where_guan)
                    ->where($where_top)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['username','tel']);
				$row->getRelation('vehicle')->visible(['name']);
				$row->getRelation('carcategory')->visible(['name']);
				$row->getRelation('province')->visible(['name']);
				$row->getRelation('city')->visible(['name']);
				$row->getRelation('area')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['province']=db('area')->where('id',$row['province_id'])->value('name');
            $row['city']=db('area')->where('id',$row['city_id'])->value('name');
            $row['area']=db('area')->where('id',$row['area_id'])->value('name');
            $row['imagelist']=explode(',',$row['content_images']);
            //如果是申请中和未发布的，查询有没有购买置顶的
            if($row['authen']!='2')
            {
                if(!$row['index_top_endtime'])
                {
                    $row['index_top_endtime']=0;
                }
                $info=db('user_circle_price')->where(['ispay'=>'1','pay_time'=>['gt',$row['index_top_endtime']]])->where(" FIND_IN_SET(".$row['id'].",circle_id)")->find();
                //更新置顶
                if($info)
                {
                    if($info['index_top']>0)
                    {
                        $row['index_top_time']=time();
                        $row['index_top_endtime']=strtotime('+'.$info['index_top'].' days');
                        $row['index_top_paytime']=time();
                    }
                    if($info['cate_top']>0)
                    {
                        $row['cate_top_time']=time();
                        $row['cate_top_endtime']=strtotime('+'.$info['cate_top'].' days');
                        $row['cate_top_paytime']=time();
                    }
                }
            }
            
            //判断是否置顶
            $row['is_top_index']=0;
            $row['is_top_cate']=0;
            $row['index_topstr']='不置顶';
            $row['cate_topstr']='不置顶';
            if($row['index_top_endtime']>time())
            {
                $row['is_top_index']=1;
                $row['index_topstr']='置顶';
            }
            if($row['cate_top_endtime']>time())
            {
                $row['is_top_cate']=1;
                $row['cate_topstr']='置顶';
            }

            
            $this->view->assign('row', $row);
            //查询发帖人信息
            $user=db('user')->where(['user_id'=>$row['user_id']])->find();
            $this->view->assign('user', $user);
            // 查询拒绝原因
            $reasonModel = new Reason();
            $reason_list = $reasonModel->order('id asc')->select()->toArray();
            $this->view->assign('reason_list',$reason_list);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            //判断是否是强制隐藏
            if($row['isshow_pt']=='1' && $params['isshow_pt']=='2')
            {
                //强制隐藏，修改强制下架时间
                $params['pt_time']=time();
                if($params['pt_reason']=='')
                {
                    $this->error(__('请填写强制隐藏原因', ''));
                }
            }
            //判断是否是审核发布
            if($row['authen']=='1' && $params['authen']!='1')
            {
                //审核
                $params['authen_time']=time();
                if($params['reason']=='' && $params['authen']=='3')
                {
                    $this->error(__('请填写拒绝原因', ''));
                }
                //如果是审核通过，并且有分类置顶或者首页置顶
                //判断分类置顶截止时间以后有没有购买置顶
                if($params['authen']=='2')
                {
                    $params['istong']=1;
                    if(!$row['index_top_endtime'])
                    {
                        $row['index_top_endtime']=0;
                    }
                    //$info=db('user_circle_price')->where(['ispay'=>'1','pay_time'=>['gt',$row['index_top_endtime']]])->where(" FIND_IN_SET(".$row['id'].",circle_id)")->find();
                    $info=db('user_circle_price')->where(" FIND_IN_SET(".$row['id'].",circle_id)")->where("price",">",0)->order("id","desc")->find();
                    //更新置顶
                    if($info)
                    {
                        if($info['ispay'] == '1' && (($info['pay_time'] > $row['index_top_endtime']) || ($info['pay_time'] > $row['cate_top_endtime']))){
                            if($info['index_top']>0)
                            {
                                $params['index_top_time']=time();
                                $params['index_top_endtime']=strtotime('+'.$info['index_top'].' days');
                                $params['index_top_paytime']=time();
                            }
                            if($info['cate_top']>0)
                            {
                                $params['cate_top_time']=time();
                                $params['cate_top_endtime']=strtotime('+'.$info['cate_top'].' days');
                                $params['cate_top_paytime']=time();
                            }
                        }else{
                            $this->error(__('置顶帖子未支付不允许操作', ''));
                        }
                    }
                }
            }
            $result = $row->allowField(true)->save($params);
            //如果是拒绝，退款
            if($result)
            {
                if(isset($params['authen']))
                {
                    if($params['authen']=='3')
                    {
                        //拒绝，
                        $user_circle_price_id=$row['user_circle_price_id'];
                        $user_circleinfo=db('user_circle_price')->where(['id'=>$user_circle_price_id])->find();
                        //修改为已退
                        db('user_circle_price')->where(['id'=>$user_circle_price_id])->update(['istui'=>1]);
                        $wxpay = new WxPay;
                        $order_no=time().rand(1,100);
                        $refund=$user_circleinfo['price'];
                        if($refund>0)
                        {
                            $total=$user_circleinfo['price'];
//                            $refund=1;
//                            $total=1;
                            $reason='帖子退款';
                            $refund_result=$wxpay->Refund($user_circleinfo['transaction_id'],$order_no,$refund,$total,$reason);
                            if($refund_result)
                            {
                                if($refund_result['code']!=1)
                                {
                                    Db::rollback();
                                    $this->error($refund_result['msg']);
                                }
                            }
                        }
                        
                    }
                }
                
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
